package com.seeyon.apps.kk.listener;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.common.collect.Lists;
import com.seeyon.apps.collaboration.event.CollaborationProcessEvent;
import com.seeyon.apps.collaboration.event.CollaborationStartEvent;
import com.seeyon.apps.collaboration.event.CollaborationStopEvent;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.filemanager.Constants.ATTACHMENT_TYPE;
import com.seeyon.ctp.common.filemanager.dao.AttachmentDAO;
import com.seeyon.ctp.common.filemanager.manager.FileManager;
import com.seeyon.ctp.common.po.affair.CtpAffair;
import com.seeyon.ctp.common.po.filemanager.Attachment;
import com.seeyon.ctp.common.po.filemanager.V3XFile;
import com.seeyon.ctp.common.po.template.CtpTemplate;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.UUIDLong;
import com.seeyon.ctp.util.annotation.ListenEvent;
import com.seeyon.kk.utils.CAP4FormKitUtils;
import com.seeyon.kk.utils.ValueUtils;
/**
 * 其它类型单据的审批 规范  固定审批1--9
 * @author Administrator
 *
 */
public class MemberTongListtener extends BaseListener {
	
	private final Log log = LogFactory.getLog(MemberTongListtener.class);

	private AttachmentDAO attachmentDAO;
	private FileManager fileManager;
	private OrgManager  orgManager;

	public AttachmentDAO getAttachmentDAO() {
		return attachmentDAO;
	}

	public void setAttachmentDAO(AttachmentDAO attachmentDAO) {
		this.attachmentDAO = attachmentDAO;
	}

	public FileManager getFileManager() {
		return fileManager;
	}

	public void setFileManager(FileManager fileManager) {
		this.fileManager = fileManager;
	}

	public OrgManager getOrgManager() {
		return orgManager;
	}

	public void setOrgManager(OrgManager orgManager) {
		this.orgManager = orgManager;
	}

	@ListenEvent(event = CollaborationStartEvent.class)
	public void onStart(CollaborationStartEvent event) throws Exception {
		Thread.sleep(BaseListener.LISTENER_THREAD_SLEEPTIME);

		String templetSubject =ValueUtils.getConfig().getString("kk.MemberShenPiFenPeiListtener"); 
			
		ColSummary summary = this.colManager.getColSummaryById(event.getSummaryId()); // 获取协同信息
		CtpTemplate template = this.templateManager.getCtpTemplate(summary.getTempleteId());
		String[] templetSubjects = StringUtils.split(templetSubject, ",");

		if (null == template) {
			return;
		}
		System.out.println("faqikaishi==========>>");
		if (ArrayUtils.contains(templetSubjects, template.getTempleteNumber())) {

			FormBean formBean = this.formManager.getFormByFormCode(template);
			FormDataMasterBean formMasterBean = this.formManager.getDataMasterBeanById(summary.getFormRecordid(),
					formBean, null);
			Map<String, Object> formdata = formMasterBean.getAllDataMap();
			
			Long attReferenceid = MapUtils.getLong(formdata, "起草-签名");
			if (attReferenceid != null) {
				//this.attachmentDAO.deleteByReference(attReferenceid);
			}
			Long defaultYesImageId = ValueUtils.getConfig().getLong("kk.defaultYesImageId");
			V3XFile defaultYesImageFile = this.fileManager.getV3XFile(defaultYesImageId);
			long subReference = UUIDLong.longUUID();
			Attachment att = new Attachment(defaultYesImageFile, ApplicationCategoryEnum.collaboration,
					ATTACHMENT_TYPE.IMAGE);
			att.setReference(event.getSummaryId());
			att.setSubReference(subReference);
			att.setIdIfNew();				  
			this.attachmentDAO.save(att);
			CAP4FormKitUtils.setCellValue(formMasterBean, "起草-签名", subReference);
		 
			this.formManager.saveOrUpdateFormData(formMasterBean, formBean.getId(), true);

		}

	}
	@ListenEvent(event = CollaborationStopEvent.class)
	public void  onStop(CollaborationStopEvent event) throws Exception{
		/*Thread.sleep(BaseListener.LISTENER_THREAD_SLEEPTIME);*/

		String templetSubject = ValueUtils.getConfig().getString("kk.MemberShenPiFenPeiListtener");

		String[] templetSubjects = StringUtils.split(templetSubject, ",");

		if (ArrayUtils.contains(templetSubjects, event.getTemplateCode())) {
			ColSummary summary = this.colManager.getColSummaryById(event.getSummaryId()); // 获取协同信息
			CtpTemplate template = this.templateManager.getCtpTemplate(summary.getTempleteId());
			FormBean formBean = this.formManager.getFormByFormCode(template);
			FormDataMasterBean formMasterBean = this.formManager.getDataMasterBeanById(summary.getFormRecordid(),
					formBean, null);
			Map<String, Object> formdata = formMasterBean.getAllDataMap();

			CtpAffair affair = event.getAffair();
		 
			Boolean needSave = false;

			// 这里需要根据用户 获取到个性化的签名，如果没有 则使用默认的
			Long defaultNoImageId = ValueUtils.getConfig().getLong("kk.defaultNoImageId");
			V3XFile defaultNoImageFile = this.fileManager.getV3XFile(defaultNoImageId);
			Long defaultYesImageId = ValueUtils.getConfig().getLong("kk.defaultYesImageId");
			V3XFile defaultYesImageFile = this.fileManager.getV3XFile(defaultYesImageId);
			V3XFile vfile = defaultYesImageFile;
			List<Map<String, Object>> affairCommentVl = this.jdbcTemplate
					.queryForList("select * from ctp_comment_all where affair_id=?", affair.getId());
			V3xOrgMember aMember=this.orgManager.getMemberById(affair.getMemberId());
			
			
			String commentString = "";
			boolean dealAttitude = true;
			for (Iterator<Map<String, Object>> iterator = affairCommentVl.iterator(); iterator.hasNext();) {
				Map<String, Object> map = iterator.next();
				Date _cdate = (Date)map.get("create_date");
				commentString=DateFormatUtils.format(_cdate, "yyyy-MM-dd");
				dealAttitude = !"collaboration.dealAttitude.disagree".equals(MapUtils.getString(map, "ext_att1"));
				vfile = dealAttitude ? defaultYesImageFile : defaultNoImageFile;
			}

			for (int i = 1; i <= 10; i++) {
				if (needSave) {
					// 有一个意见匹配需要更新
					break;
				}
				FormFieldBean spFfb = formMasterBean.getFormTable().getFieldBeanByDisplay("审批"+i );
				if(spFfb==null){
					continue;
				}
				Long memberId = MapUtils.getLong(formdata, spFfb.getName());

				if (affair.getMemberId().equals(memberId)) {
					// 赋值意见和态度
					//CAP4FormKitUtils.setCellValue(formMasterBean, "审批-意见" + i, commentString);
					CAP4FormKitUtils.setCellValue(formMasterBean, "审批"+ i+"-日期", commentString);
					CAP4FormKitUtils.setCellValue(formMasterBean, "审批"+ i+"-职位" , aMember.getOrgPostId());
					needSave = true;
					FormFieldBean spImagefb = formMasterBean.getFormTable().getFieldBeanByDisplay("审批"+ i+"-签名");
					Long attReferenceid = MapUtils.getLong(formdata, spImagefb.getName());
					if (attReferenceid != null) {
						//this.attachmentDAO.deleteByReference(attReferenceid);
					}
					long subReference = UUIDLong.longUUID();
					Attachment att = new Attachment(vfile, ApplicationCategoryEnum.collaboration,
							ATTACHMENT_TYPE.IMAGE);
					att.setReference(event.getSummaryId());
					att.setSubReference(subReference);
					att.setIdIfNew();				  
					this.attachmentDAO.save(att);
					CAP4FormKitUtils.setCellValue(formMasterBean, "审批"+ i+"-签名", subReference);
				} 

			}
			if (needSave) {
				this.formManager.saveOrUpdateFormData(formMasterBean, formBean.getId(), true);
			}

		}
	}

	@ListenEvent(event = CollaborationProcessEvent.class,async = true)
	public void onProcess(CollaborationProcessEvent event) throws Exception {
		Thread.sleep(BaseListener.LISTENER_THREAD_SLEEPTIME);

		String templetSubject = ValueUtils.getConfig().getString("kk.MemberShenPiFenPeiListtener");

		String[] templetSubjects = StringUtils.split(templetSubject, ",");

		if (ArrayUtils.contains(templetSubjects, event.getTemplateCode())) {
			ColSummary summary = this.colManager.getColSummaryById(event.getSummaryId()); // 获取协同信息
			CtpTemplate template = this.templateManager.getCtpTemplate(summary.getTempleteId());
			FormBean formBean = this.formManager.getFormByFormCode(template);
			FormDataMasterBean formMasterBean = this.formManager.getDataMasterBeanById(summary.getFormRecordid(),
					formBean, null);
			Map<String, Object> formdata = formMasterBean.getAllDataMap();

			//各个节点可以更换审批人或协议人 start
			List<String> sp = Lists.newArrayList();
			List<String> xy = Lists.newArrayList();

			for (int i = 1; i <= 9; i++) {
				FormFieldBean spFfb = formMasterBean.getFormTable().getFieldBeanByDisplay("审批" + i);
				FormFieldBean lxFfb = formMasterBean.getFormTable().getFieldBeanByDisplay("类型" + i);
				String member = MapUtils.getString(formdata, spFfb.getName());
				/*String stype = MapUtils.getString(formdata, lxFfb.getName());*/
				if (StringUtils.isNotEmpty(member)) {
					sp.add(member);
					/*if (StringUtils.equals(ValueUtils.getConfig().getString("kk.ApprovalEnumId"), stype)) {
						sp.add(member);
					} else {
						xy.add(member);
					}*/

				}

			}
			System.out.println("xiugaikiashi------------>>"+sp.size());
		    //第1到4的审批控件 是审批类型	
			for (int i = 1; i <= 9; i++) {
				String mv="";
				if (sp.size() >= i) {
					mv = sp.get(i - 1);
				}
				String fieldDisplayName = "审批"+ i+"-姓名" ;
				CAP4FormKitUtils.setCellValue(formMasterBean, fieldDisplayName, mv);
			}
            //第5到9的审批控件 是协议类型
			/*for (int i = 5; i <= 9; i++) {
				String mv="";
				if (xy.size() >= (i-4)) {
					mv = xy.get(i - 5);
				}
				String fieldDisplayName = "审批"+ i+"-姓名" ;

				CAP4FormKitUtils.setCellValue(formMasterBean, fieldDisplayName, mv);
			}*/
			//各个节点可以更换审批人或协议人 end
			
			
			
			CtpAffair affair = event.getAffair();
			Boolean needSave = false;

			// 这里需要根据用户 获取到个性化的签名，如果没有 则使用默认的
			Long defaultNoImageId = ValueUtils.getConfig().getLong("kk.defaultNoImageId");
			V3XFile defaultNoImageFile = this.fileManager.getV3XFile(defaultNoImageId);
			Long defaultYesImageId = ValueUtils.getConfig().getLong("kk.defaultYesImageId");
			V3XFile defaultYesImageFile = this.fileManager.getV3XFile(defaultYesImageId);
			V3XFile vfile = defaultYesImageFile;
			List<Map<String, Object>> affairCommentVl = this.jdbcTemplate
					.queryForList("select * from ctp_comment_all where affair_id=?", affair.getId());
			String commentString = "";
			boolean dealAttitude = true;
			for (Iterator<Map<String, Object>> iterator = affairCommentVl.iterator(); iterator.hasNext();) {
				Map<String, Object> map = iterator.next();
				Date _cdate = (Date)map.get("create_date");
				commentString=DateFormatUtils.format(_cdate, "yyyy-MM-dd");
				dealAttitude = !"collaboration.dealAttitude.disagree".equals(MapUtils.getString(map, "ext_att1"));
				vfile = dealAttitude ? defaultYesImageFile : defaultNoImageFile;
			}
			V3xOrgMember aMember=this.orgManager.getMemberById(affair.getMemberId());

			for (int i = 1; i <= 10; i++) {
				if (needSave) {
					// 有一个意见匹配需要更新
					break;
				}
				FormFieldBean spFfb = formMasterBean.getFormTable().getFieldBeanByDisplay("审批"+ i+"-姓名" );
				if(spFfb==null){
					continue;
				}

				Long memberId = MapUtils.getLong(formdata, spFfb.getName());

				if (affair.getMemberId().equals(memberId)) {
					// 赋值意见和态度
					//CAP4FormKitUtils.setCellValue(formMasterBean, "审批-意见" + i, commentString);
					CAP4FormKitUtils.setCellValue(formMasterBean, "审批"+ i+"-日期", commentString);
					CAP4FormKitUtils.setCellValue(formMasterBean, "审批"+ i+"-职位" , aMember.getOrgPostId());
					needSave = true;
					FormFieldBean spImagefb = formMasterBean.getFormTable().getFieldBeanByDisplay("审批"+ i+"-签名");
					Long attReferenceid = MapUtils.getLong(formdata, spImagefb.getName());
					if (attReferenceid != null) {
						//this.attachmentDAO.deleteByReference(attReferenceid);
					}
					long subReference = UUIDLong.longUUID();
					Attachment att = new Attachment(vfile, ApplicationCategoryEnum.collaboration,
							ATTACHMENT_TYPE.IMAGE);
					att.setReference(event.getSummaryId());
					att.setSubReference(subReference);
					att.setIdIfNew();				  
					this.attachmentDAO.save(att);
					CAP4FormKitUtils.setCellValue(formMasterBean, "审批"+ i+"-签名", subReference);
				} 
			}
			if (needSave) {
				this.formManager.saveOrUpdateFormData(formMasterBean, formBean.getId(), true);
			}

		}
	}

}
